const log = require('../util/log'),
SQL_TABLE = 'url_word',
SQL_SELECT = 'select url as urlId,word as wordId,p from ' + SQL_TABLE;

exports.matchWordId = (wordId, fn) => {
	fn = fn || (() => {});
	global.pool.query(SQL_SELECT + ' where word=?', [wordId], (err, rows, fields) => {
		if (err)
			throw err;
		fn(rows)
	})
}

exports.matchUrlId = (urlId, fn) => {
	fn = fn || (() => {});
	global.pool.query(SQL_SELECT + ' where url=?', [urlId], (err, rows, fields) => {
		if (err)
			throw err;
		fn(rows)
	})
}

exports.insert = (uw, fn) => {
	fn = fn || (() => {});
	uw.p = uw.p || 0;
	global.pool.query('insert into ' + SQL_TABLE + '(url,word,p) values(?,?,?)', [uw.urlId, uw.wordId, uw.p], (err, result) => {
		if (err) {
			if (err.code == 'ER_DUP_ENTRY')
				fn();
			else
				throw err;
		} else {
			fn()
		}
	})
}

exports.multiplyPByUrlIdAndNotWordId = (lr, urlId, wordId, fn) => {
	fn = fn || (() => {});
	global.pool.query('update ' + SQL_TABLE + ' set p=p*? where url=? and word!=?', [lr, urlId, wordId], (err, result) => {
		if (err)
			throw err;
		fn()
	})
}

exports.update = (uw, fn) => {
	fn = fn || (() => {});
	global.pool.query('update ' + SQL_TABLE + ' set p=? where url=? and word=?', [uw.p, uw.urlId, uw.wordId], (err, result) => {
		if (err)
			throw err;
		fn()
	})
}

exports.findByUrlIdWordId = (urlId, wordId, fn) => {
	fn = fn || (() => {});
	global.pool.query(SQL_SELECT + ' where url=? and word=?', [urlId, wordId], (err, rows, fields) => {
		if (err)
			throw err;
		if (rows.length > 0)
			fn(rows[0]);
		else
			fn(null)
	})
}

exports.searchUrl = (wordId, page, fn) => {
	fn = fn || (() => {});
	global.pool.query('select A.url as urlId,A.word as wordId,A.p as p from url_word A inner join url B on A.url=B.id where A.word=? order by A.p*B.p desc limit ?,10', [wordId, (page - 1) * 10], (err, rows, fields) => {
		if (err)
			throw err;
		fn(rows)
	})
}

exports.searchWord = (urlId, fn) => {
	fn = fn || (() => {});
	global.pool.query(SQL_SELECT + ' where url=? order by p desc limit 0,3', [urlId], (err, rows, fields) => {
		if (err)
			throw err;
		fn(rows)
	})
}

exports.deleteByUrlId = (urlId, resolve) => {
	resolve = resolve || (() => {});
	global.pool.query('delete from ' + SQL_TABLE + ' where url=?', [urlId], (err, result) => {
		if (err)
			throw err;
		resolve()
	})
}

exports.delete = (urlId, wordId, resolve) => {
	resolve = resolve || (() => {});
	global.pool.query('delete from ' + SQL_TABLE + ' where url=? and word=?', [urlId, wordId], (err, result) => {
		if (err)
			throw err;
		resolve()
	})
}
